
#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""
    @author jay.han
"""
import logging
import socket
from cvirt.common import constant
from cvirt.cnode.guest import guest_utils as utils

TIMEOUT = 5
LOG = logging.getLogger('cvirt.guest.api')

class GuestAPI(object):
    """
     vm api
    """
    CHANGE_HOSTNAME = '0x01'
    CHANGE_IP = '0x02'
    ADD_USER = '0x03'
    ROBOOT = '0x04'
    def __init__(self):
        self.prefix = '#'

    def _connect_and_send(self,name,message):
        try:
            _s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
            _s.connect(constant.getGuestAgentPath(name))
            _s.settimeout(TIMEOUT)
            _s.send(message)
            result = _s.recv(2048)

        except Exception as e:
            LOG.exception('error in connect to unix channel %s' % name)
            return False
        finally:
            _s.close()

        return self._parse_result(result)

    def _parse_result(self,result):
        return result.split('#')

    def change_guest_name_offline(self,instance_name,instance_path):
        """
            use libguestfs to add register file to vm
        :param instance_name:
        :param instance_path:
        :return:
        """
        return utils.change_host_name_offline(instance_name,instance_path)

    def change_guest_name(self,instance_name,host_name):
        return self._connect_and_send(instance_name,'%s%s%s'%(self.CHANGE_HOSTNAME,self.prefix,host_name))

    def change_guest_ip(self,instance_name,guest_ip,netmask,gateway):
        return self._connect_and_send(instance_name,'%s%s%s,%s,%s'%(self.CHANGE_IP,self.prefix,
                                                                    guest_ip,netmask,gateway))


    def add_user(self,instance_name,user_name,password):
        return self._connect_and_send(instance_name,'%s%s%s,%s'%(self.CHANGE_IP,self.prefix,user_name,password))

api = GuestAPI()


